package day04;

/**
 * <a href="https://leetcode-cn.com/problems/reverse-integer/">7. 整数反转</a>
 */
public class Answer {

    public static void main(String[] args) {

        System.out.println(reverse3(1234567819));
//        long i = 9876542221L;
//        System.out.println((int)i);
    }

    public static int reverse(int x) {
        if (Math.abs(x) > (Math.pow(2, 32) - 1)) {
            return 0;
        }
        boolean positive = true;
        if (x < 0) {
            x = Math.abs(x);
            positive = false;
        }
        StringBuilder sb = new StringBuilder(String.valueOf(x)).reverse();
        int i = 0;
        try {
            i = Integer.parseInt(sb.toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return positive ? i : -i;
    }

    public static int reverse1(int x) {
        long n = 0;
        while (x != 0) {
            n = n * 10 + x % 10;
            x = x / 10;
        }
        return (int) n == n ? (int) n : 0; // 将第一个n强转为int类型与long类型做对比，避免溢出问题
    }

    // 全部转换为负数
    public static int reverse2(int x) {
        // 右位移31位，并做与运算，得到是否为负数
        boolean neg = ((x >>> 31) & 1) == 1;
        x = neg ? x : -x;
        int m = Integer.MIN_VALUE / 10;
        int o = Integer.MIN_VALUE % 10;
        int res = 0;
        while (x != 0) {
            if (res < m || (res == m && x % 10 < o)) {
                return 0;
            }
            res = res * 10 + x % 10;
            x /= 10;
        }
        return neg ? res : Math.abs(res);
    }

    public static int reverse3(int x) {
        int res = 0;
        int last;
        while (x != 0) {
            //每次取末尾数字
            int tmp = x % 10;
            last = res;
            res = res * 10 + tmp;
            //判断整数溢出：如果不相等，说明已经溢出
            if (last != res / 10) {
                return 0;
            }
            x /= 10;
        }
        return res;
    }
}
